//
//  PersonListVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/11/27.
//

import Foundation
import UIKit

class PersonListVC: SubLevelViewController, PullToRefreshPresentable {
    let tableView = UITableView(frame: .zero, style: .plain)
    let submitBtn = UIButton.createPrimaryLarge("提交")

    var datas: [PersonModal?] = []
    var selectDatas: [PersonModal] = []

    var pageNum: Int = 1
    var totalPage: Int64 = 0
    var param: PersonParam = PersonParam(pageSize: 500)

    var isMutli: Bool = false
    var userType: String = "00"

    open var didSelectPersonsWith:((_ names: String?) -> ())?
    open var didSelectPersonWith:((_ person: PersonModal) -> ())?

    init(withUserType _userType: String? = "00", Mutli _isMutli: Bool? = false, company: CompanyModal? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.param.userType = _userType
        self.param.companyId = company?.id
        self.userType = _userType ?? "00"
        self.isMutli = _isMutli ?? false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        title = "人员列表"
        
        pageNum = 1
        setupUI()
        setupNavItems()
        setupPullToRefresh(on: tableView)
        reloadData()
    }
    
    deinit {
        tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        reloadData()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        reloadData()
    }
    
    func reloadData() {
        param.pageNum = pageNum
        API.getPeoples(withParam: param) { responseModel in
            DispatchQueue.main.async {
                if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                    self.pageNum -= 1
                    return
                }
                if self.pageNum == 1 {
                    self.datas.removeAll()
                }
                self.totalPage = responseModel.totalPage
                self.datas.append(contentsOf: responseModel.models ?? [])
                self.tableView.tableShowEmpty(withDataCount: self.datas.count)
                self.tableView.reloadData()
            }
        }
    }
    
    @objc func confirmTapped() {
        var nameArr: [String] = []
        selectDatas.forEach {
            if let name = $0.nickName {
                nameArr.append(name)
            }
        }
        let names = nameArr.joined(separator: "，")
        didSelectPersonsWith?(names)
        navigationController?.popViewController(animated: true)
    }
    
    @objc func searchTapped() {
        let listV = PersonSearchVC()
        listV.didSelectItemWith = { (name, job, phone) -> () in
            self.param.nickName = name
            self.param.jobNum = job
            self.param.phonenumber = phone
            self.pageNum = 1
            self.reloadData()
        }
        navigationController?.pushViewController(listV, animated: true)
    }
    
    func handlePersonDetail(modal: PersonModal?) {
        if let m = modal {
            let detailV = PersonEditVC(withModal: m)
            navigationController?.pushViewController(detailV, animated: true)
        }
    }
    
    func handlePersonSelect(modal: PersonModal?) {
        if let m = modal {
            if isMutli {
                var index = -1
                for (i, element) in selectDatas.enumerated() {
                    if element.userId == m.userId {
                        index = i
                    }
                }
                if index >= 0 {
                    selectDatas.remove(at: index)
                } else {
                    selectDatas.append(m)
                }
                tableView.reloadData()
            } else {
                didSelectPersonWith?(m)
                navigationController?.popViewController(animated: true)
            }
        }
    }
    
    // MARK: - Setup
    
    func setupUI() {
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)

        if isMutli {
            submitBtn.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside)
            view.addSubview(submitBtn)
            submitBtn.snp.makeConstraints { (make) -> Void in
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-10)
                make.height.equalTo(50)
                make.centerX.equalTo(view.snp.centerX)
                make.width.equalTo(ScreenWidth - 20)
            }
            
            tableView.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
                make.bottom.equalTo(submitBtn.snp.top).offset(-10)
            }
        } else {
            tableView.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            }
        }
    }
    
    func setupNavItems() {
        let searchBtn = UIButton(type: .custom)
        searchBtn.setImage(UIImage(named: "ic_search"), for: .normal)
        searchBtn.addTarget(self, action: #selector(searchTapped), for: .touchUpInside)
        searchBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        searchBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
        let searchBar = UIBarButtonItem(customView: searchBtn)

        navigationItem.rightBarButtonItems = [searchBar]
    }
}

extension PersonListVC: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datas[indexPath.row]
        let ID : String = "PersonListCell"
            
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil {
            cell = PersonListCell(style: .subtitle, reuseIdentifier: ID)
        }
        
        (cell as? PersonListCell)?.didSelectItemWith = { () -> () in
            self.handlePersonSelect(modal: data)
        }
        (cell as? PersonListCell)?.didSelectDetailWith = { () -> () in
            self.handlePersonDetail(modal: data)
        }
        
        let isSel = selectDatas.filter({$0.userId == data?.userId}).count > 0
        (cell as? PersonListCell)?.reload(withModal: data, isSel: isSel, isMutli: isMutli, userType: userType)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }

//    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let data = datas[indexPath.row]
//        navigationController?.pushViewController(NotiDetailVC(id: data?.noticeId), animated: true)
//        if let modal = datas[indexPath.row] {
//            if isMutli {
//                var index = -1
//                for (i, element) in selectDatas.enumerated() {
//                    if element.userId == modal.userId {
//                        index = i
//                    }
//                }
//                if index >= 0 {
//                    selectDatas.remove(at: index)
//                } else {
//                    selectDatas.append(modal)
//                }
//                tableView.reloadData()
//            } else {
//                didSelectPersonWith?(modal)
//                navigationController?.popViewController(animated: true)
//            }
//        }
//    }
}

